package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.MemberLevel;
import com.zuipin.enums.IntegralType;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.mapper.IntegralRecordMapper;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;

/**
 * @ClassName: IntegralRecordServiceImpl
 * @author wuyicheng
 * @time 2017年3月27日下午4:03:17
 */
@Service
public class IntegralRecordServiceImpl implements IIntegralRecordService {
	@Resource
	private IntegralRecordMapper	integralRecordMapper;
	@Resource
	private IMemberAccountService	memberAccountService;
	
	/**
	 * @Title: findById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:20:14
	 * @param id
	 * @return
	 * @throws
	 */
	@Override
	public IntegralRecord findById(Long id) {
		return integralRecordMapper.findById(id);
	}
	
	/**
	 * @Title: findList
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:20:14
	 * @param integralRecord
	 * @return
	 * @throws
	 */
	@Override
	public List<IntegralRecord> findList(IntegralRecord integralRecord) {
		return null;
	}
	
	/**
	 * @Title: insert
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:20:14
	 * @param integralRecord
	 * @throws
	 */
	@Override
	public void insert(IntegralRecord integralRecord) {
		integralRecord.setCreateTime(DateUtils.getCurrentDateTime());
		integralRecord.setUpdateTime(DateUtils.getCurrentDateTime());
		integralRecord.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		integralRecordMapper.insert(integralRecord);
	}
	
	/**
	 * @Title: update
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:20:14
	 * @param integralRecord
	 * @throws
	 */
	@Override
	public void update(IntegralRecord integralRecord) {
		integralRecord.setUpdateTime(DateUtils.getCurrentDateTime());
		integralRecordMapper.update(integralRecord);
	}
	
	/**
	 * @Title: deleteById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:20:14
	 * @param id
	 * @throws
	 */
	@Override
	public void deleteById(Long id) {
		IntegralRecord integralRecord = integralRecordMapper.findById(id);
		integralRecord.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
		update(integralRecord);
		
	}
	
	/**
	 * @throws CustomException 
	 * 会员积分变更
	 *
	 * @Title: addIntegralRecord 
	 * @author: wuyicheng
	 * @date: 2017年4月25日下午6:08:14 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param createId 创建者ID
	 * @param updateId 修改者ID
	 * @param alterPoint 操作积分
	 * @param integralType 积分类型
	 * @param remark 备注
	 * @param isBuy 是不是购买  1是 0否
	 * 
	 * @throws
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void addIntegralRecord(Long memberId, Long sysId, Long createId, Long updateId, Integer alterPoint, IntegralType integralType, String remark, String describe,
			String oddNumbers, Short isBuy) throws CustomException {
		
		// MemberAccount memberAccount = memberAccountService.findByMemberIdAndSysId(memberId, sysId);
		MemberAccount memberAccount = memberAccountService.findByMemberIdAndSysIdForUpdate(memberId, sysId);
		if (memberAccount != null) {
			/*boolean isBinding = memberAccountService
					.isBindingMobilePhone(memberAccount.getMemberId());
			//账号未绑定手机号，不能操作
			if (!isBinding) {
				throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(),
						"Account not binding mobile phone number, can't operation");
			}*/
			if (!(MemberLevel.AGENT_MEMBER_LEVEL_ID.equals(memberAccount.getMemberLevelId())) && alterPoint != 0) {
				IntegralRecord integralRecord = new IntegralRecord();
				integralRecord.setMemberId(memberId);
				integralRecord.setSysId(sysId);
				integralRecord.setCreateId(createId);
				integralRecord.setUpdateId(updateId);
				integralRecord.setIntegralType(integralType);
				integralRecord.setBeforePoint(memberAccount.getTotalIntegral());
				integralRecord.setAlterPoint(alterPoint);
				integralRecord.setDescribes(describe);
				integralRecord.setOddNumbers(oddNumbers);
				// 修改后的金额
				int totalIntegral = memberAccount.getTotalIntegral() == null ? 0 : memberAccount.getTotalIntegral();
				
				// int cumulativeIntegral = memberAccount.getCumulativeIntegral() == null ? 0
				// : memberAccount.getCumulativeIntegral();
				// USE_SHOPPING购物积分抵扣 减少
				// 其余默认都是增加
				// if (IntegralType.USE_SHOPPING.equals(integralType)) {
				// totalIntegral = totalIntegral - alterPoint;
				// integralRecord.setAlterPoint(-alterPoint);
				// } else {//积分增加累计积分增加
				// totalIntegral = totalIntegral + alterPoint;
				// cumulativeIntegral = cumulativeIntegral + alterPoint;
				// integralRecord.setAlterPoint(alterPoint);
				// }
				totalIntegral = totalIntegral + alterPoint;
				integralRecord.setAlterPoint(alterPoint);
				integralRecord.setAfterPoint(totalIntegral);
				// 可用积分小于使用积分，不能操作
				if (totalIntegral < 0 && alterPoint < 0) {
					if (IntegralRecord.IS_BUY_YES == isBuy) {
						throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "积分不足");
					} else {
						integralRecord.setAfterPoint(0);
						integralRecord.setAlterPoint(-1 * (memberAccount.getTotalIntegral() == null ? 0 : memberAccount.getTotalIntegral()));
					}
				}
				
				integralRecord.setRemark(remark);
				insert(integralRecord);// 新增记录
				// 更新账户
				MemberAccount tempMemberAccount = new MemberAccount();
				tempMemberAccount.setId(memberAccount.getId());
				tempMemberAccount.setTotalIntegral(totalIntegral);
				// tempMemberAccount.setCumulativeIntegral(cumulativeIntegral);
				// memberAccountService.update(tempMemberAccount);
				memberAccountService.updateIntegral(memberAccount.getId(), integralRecord.getAlterPoint());
				
			}
		} else {
			throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "memberAccount is not exist");
		}
	}
	
	/**
	 * @throws CustomException  
	 * 根据总价和会员等级计算赠送积分
	 * 
	 * @Title: getGiveIntegral 
	 * @author: wuyicheng
	 * @date: 2017年6月16日上午10:50:11 
	 * @param subtotal
	 * @param memberLevel
	 * @return
	 * @throws 
	 */
	@Override
	public Integer getGiveIntegral(BigDecimal subtotal, MemberLevel memberLevel) throws CustomException {
		// 积分消费比例1:1,指每消费满1元，送一个积分，不足1元不赠送，向下取整
		if (memberLevel != null) {
			BigDecimal integralMultiple = memberLevel.getIntegralMultiple();
			BigDecimal consumIntegralRatio = memberLevel.getConsumIntegralRatio();
			// 消费积分比例(积分值/消费值)
			subtotal = ArithUtil.mul(subtotal, consumIntegralRatio, 2);
			Integer giveIntegral = ArithUtil.mul(subtotal, integralMultiple, 2).intValue();
			return giveIntegral;
		} else {
			throw new CustomException(ErrorCode.MEMBER_LEVEL_IS_NULL.getCode(), "会员等级异常");
		}
	}
	
	@Override
	public List<IntegralRecord> findListByPage(IntegralRecord ir, Pagination page) {
		// TODO Auto-generated method stub
		return integralRecordMapper.findListByPage(ir, page);
	}
	
	@Override
	public Integer getCurrentIntegral(Long memberId, Long sysId) {
		// TODO Auto-generated method stub
		return integralRecordMapper.getCurrentIntegral(memberId, sysId);
	}
	
}
